"""
数据质量检查工具

用于标注数据来源、质量和可信度，帮助用户理解哪些数据是直接获取的，哪些是计算推导的。
"""

from typing import Dict, Any, List, Tuple
from enum import Enum


class DataSource(Enum):
    """数据来源类型"""
    API_DIRECT = "API直接返回"
    CALCULATED = "计算推导"
    ESTIMATED = "估算值"
    MISSING = "数据缺失"
    CACHED = "缓存数据"


class DataQuality(Enum):
    """数据质量等级"""
    HIGH = "高质量"        # API直接返回，官方数据
    MEDIUM = "中等质量"    # 基于可靠数据计算
    LOW = "低质量"         # 基于估算或不完整数据计算
    UNKNOWN = "质量未知"   # 无法验证


class DataQualityChecker:
    """数据质量检查器"""
    
    def __init__(self):
        self.quality_report = {}
    
    def check_value(self, key: str, value: Any, source: DataSource = DataSource.API_DIRECT) -> Tuple[Any, Dict[str, Any]]:
        """
        检查单个数据值的质量
        
        Args:
            key: 数据字段名
            value: 数据值
            source: 数据来源
            
        Returns:
            (值, 质量信息字典)
        """
        quality_info = {
            'key': key,
            'value': value,
            'source': source.value,
            'quality': DataQuality.UNKNOWN.value,
            'issues': []
        }
        
        # 检查数据是否缺失
        if value is None or value == 0 or value == 'False' or value == '':
            quality_info['quality'] = DataQuality.LOW.value
            quality_info['issues'].append('数据缺失或为零')
            quality_info['source'] = DataSource.MISSING.value
            return value, quality_info
        
        # 根据来源判断质量
        if source == DataSource.API_DIRECT:
            quality_info['quality'] = DataQuality.HIGH.value
        elif source == DataSource.CALCULATED:
            quality_info['quality'] = DataQuality.MEDIUM.value
        elif source == DataSource.ESTIMATED:
            quality_info['quality'] = DataQuality.LOW.value
            quality_info['issues'].append('基于估算，可能不准确')
        
        # 检查数据类型一致性
        if isinstance(value, str):
            # 检查是否包含单位
            if '亿' in value or '万' in value:
                quality_info['has_unit'] = True
            if '%' in value:
                quality_info['is_percentage'] = True
        
        return value, quality_info
    
    def check_financial_data(self, data: Dict[str, Any], api_source: str = "unknown") -> Dict[str, Any]:
        """
        检查财务数据的整体质量
        
        Args:
            data: 财务数据字典
            api_source: API来源标识
            
        Returns:
            质量报告字典
        """
        report = {
            'api_source': api_source,
            'total_fields': len(data),
            'direct_fields': 0,
            'calculated_fields': 0,
            'missing_fields': 0,
            'field_details': {}
        }
        
        for key, value in data.items():
            # 判断数据来源
            if key in ['data_source', 'date', '日期', '报告期']:
                source = DataSource.API_DIRECT
            elif 'ratio' in key or 'margin' in key or '率' in key:
                # 比率类指标可能是计算的
                if isinstance(value, (int, float)) and value > 0:
                    source = DataSource.CALCULATED
                else:
                    source = DataSource.API_DIRECT
            else:
                source = DataSource.API_DIRECT
            
            _, quality_info = self.check_value(key, value, source)
            report['field_details'][key] = quality_info
            
            # 统计
            if quality_info['source'] == DataSource.API_DIRECT.value:
                report['direct_fields'] += 1
            elif quality_info['source'] == DataSource.CALCULATED.value:
                report['calculated_fields'] += 1
            elif quality_info['source'] == DataSource.MISSING.value:
                report['missing_fields'] += 1
        
        # 计算总体质量评分
        high_quality = sum(1 for f in report['field_details'].values() if f['quality'] == DataQuality.HIGH.value)
        medium_quality = sum(1 for f in report['field_details'].values() if f['quality'] == DataQuality.MEDIUM.value)
        
        total = report['total_fields']
        if total > 0:
            quality_score = (high_quality * 1.0 + medium_quality * 0.6) / total * 100
            report['quality_score'] = round(quality_score, 1)
        else:
            report['quality_score'] = 0
        
        return report
    
    def generate_quality_summary(self, report: Dict[str, Any]) -> str:
        """
        生成数据质量摘要文本
        
        Args:
            report: 质量报告字典
            
        Returns:
            质量摘要文本
        """
        summary = []
        summary.append(f"📊 数据质量报告")
        summary.append(f"  数据源: {report['api_source']}")
        summary.append(f"  总字段数: {report['total_fields']}")
        summary.append(f"  质量评分: {report['quality_score']:.1f}/100")
        summary.append(f"")
        summary.append(f"  📈 API直接字段: {report['direct_fields']} 个")
        summary.append(f"  🔢 计算推导字段: {report['calculated_fields']} 个")
        summary.append(f"  ⚠️  缺失字段: {report['missing_fields']} 个")
        
        # 添加质量评级
        if report['quality_score'] >= 80:
            summary.append(f"  ✅ 数据质量：优秀")
        elif report['quality_score'] >= 60:
            summary.append(f"  ✅ 数据质量：良好")
        elif report['quality_score'] >= 40:
            summary.append(f"  ⚠️  数据质量：一般")
        else:
            summary.append(f"  ❌ 数据质量：较差")
        
        return '\n'.join(summary)
    
    def get_field_annotation(self, key: str, quality_info: Dict[str, Any]) -> str:
        """
        获取字段的质量标注
        
        Args:
            key: 字段名
            quality_info: 质量信息
            
        Returns:
            标注文本
        """
        annotations = []
        
        # 来源标注
        if quality_info['source'] == DataSource.API_DIRECT.value:
            annotations.append("📡")  # API直接数据
        elif quality_info['source'] == DataSource.CALCULATED.value:
            annotations.append("🔢")  # 计算值
        elif quality_info['source'] == DataSource.ESTIMATED.value:
            annotations.append("📊")  # 估算值
        elif quality_info['source'] == DataSource.MISSING.value:
            annotations.append("⚠️")  # 缺失值
        
        # 质量标注
        if quality_info['quality'] == DataQuality.HIGH.value:
            annotations.append("✅")
        elif quality_info['quality'] == DataQuality.MEDIUM.value:
            annotations.append("🔶")
        elif quality_info['quality'] == DataQuality.LOW.value:
            annotations.append("⚠️")
        
        return ' '.join(annotations)


# 全局实例
data_quality_checker = DataQualityChecker()